package com.example.scanner;

import com.example.annotation.Controller;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ClasspathScanner {

    public static List<Class<?>> findClassesWithAnnotation(String packageName, Class<? extends java.lang.annotation.Annotation> annotation)
            throws ClassNotFoundException, IOException {
        List<Class<?>> classes = new ArrayList<>();
        String path = packageName.replace('.', '/');

        // 获取类加载器
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        assert classLoader != null;

        // 获取包对应的URL
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<>();

        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(resource.getFile()));
        }

        // 遍历目录和JAR文件
        for (File directory : dirs) {
            if (directory.exists()) {
                // 如果是目录，则递归查找
               findClassesWithAnnotationInDirectory(directory, packageName, annotation, classes);
            } else if (directory.getName().endsWith(".jar")) {
                // 如果是JAR文件，则查找JAR中的类
                findClassesWithAnnotationInJar(directory, packageName, annotation, classes);
            }
        }

        return classes;
    }

    private static void findClassesWithAnnotationInDirectory(File directory, String packageName,
                                                             Class<? extends java.lang.annotation.Annotation> annotation,
                                                             List<Class<?>> classes) throws ClassNotFoundException {
        if (!directory.exists()) {
            return;
        }

        File[] files = directory.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".class");
            }
        });

        if (files != null) {
            for (File file : files) {
                // 去掉.class后缀，并将/替换为.来生成类名
                String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
                try {
                    Class<?> clazz = Class.forName(className);

                    // 检查类是否包含指定的注解
                    if (clazz.isAnnotationPresent(annotation)) {
                        classes.add(clazz);
                    }
                } catch (ClassNotFoundException e) {
                    // 忽略此异常，因为可能在子包中
                }
            }
        }
    }
    private static void findClassesWithAnnotationInJar(File jarFile, String packageName,
                                                       Class<? extends java.lang.annotation.Annotation> annotation,
                                                       List<Class<?>> classes) throws IOException, ClassNotFoundException {
        JarFile jar = new JarFile(jarFile);
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String name = entry.getName();
            if (name.charAt(0) == '/') {
                name = name.substring(1);
            }
            if (name.startsWith(packageName.replace('.', '/')) && name.endsWith(".class")) {
                // 去掉.class后缀，并将/替换为.来生成类名
                String className = name.substring(0, name.length() - 6).replace('/', '.');
                try {
                    Class<?> clazz = Class.forName(className);
                    if (clazz.isAnnotationPresent(annotation)) {
                        classes.add(clazz);
                    }
                } catch (ClassNotFoundException e) {
                    // 可能由于类加载器的问题导致无法加载，忽略
                }
            }
        }
        jar.close();
    }
    public static List<Class<?>> scanForControllers(String packageName) throws ClassNotFoundException, IOException {
        return findClassesWithAnnotation(packageName, Controller.class);
    }

}

